package org.openrbac.rbac.initialization;

import org.openrbac.rbac.constant.CommonConstant;
import org.openrbac.rbac.entity.Auth;
import org.openrbac.rbac.entity.DictDetail;
import org.openrbac.rbac.entity.User;
import org.openrbac.rbac.mapper.AuthMapper;
import org.openrbac.rbac.mapper.DictDetailMapper;
import org.openrbac.rbac.mapper.UserMapper;
import org.openrbac.rbac.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 梁富贵
 * @Date 2024/5/27
 **/
@Component
@Order(value = 1)
public class UserInitialization implements CommandLineRunner {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthMapper authMapper;

    @Autowired
    private DictDetailMapper dictDetailMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 初始化用户信息
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        initUsers();
        initAuths();
    }

    /**
     * 加载用户信息
     */
    private void initUsers() {
        List<User> users = userMapper.getAllUserPartMessage();
        users.forEach(user -> {
            redisUtil.hashSet(CommonConstant.USER_PART_MESSAGE, user.getUsername(), user);
        });
        List<User> allUser = userMapper.getAllUser();
        allUser.forEach(user -> {
            redisUtil.hashSet(CommonConstant.USER_ALL_MESSAGE, user.getUsername(), user);
        });
    }

    /**
     * 加载权限信息
     */
    private void initAuths() {
        List<Auth> auths = authMapper.getAllAuths();
        auths.forEach(auth -> {
            redisUtil.hashSet(CommonConstant.AUTHS, String.valueOf(auth.getId()), auth);
        });
    }

    /**
     * 加载字典详情信息
     */
    private void initDictDetails() {
        List<DictDetail> dictDetails = dictDetailMapper.selectList(null);
        dictDetails.forEach(dictDetail -> {
            redisUtil.hashSet(CommonConstant.DICT_DETAILS, String.valueOf(dictDetail.getId()), dictDetail);
        });
    }

}
